package bb.lanxing.lib.devices.bryton.ncs;

import android.app.Service;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

public class ExtensionHost {
    private static final String TAG = "ExtensionHost";
    public static final int UPDATE_COLLAPSE_TIME_MILLIS = 500;
    static final SparseArray<Operation> UPDATE_OPERATIONS = new SparseArray<>();
    private volatile Handler mAsyncHandler;
    private volatile Looper mAsyncLooper;
    private Context mContext;
    private ExtensionManager mExtensionManager;
    private Map<ComponentName, Connection> mExtensionConnections = new HashMap();
    private Handler mClientThreadHandler = new Handler();

    public interface Operation {
        void run(IExtension iExtension);
    }

    public ExtensionHost(Service service) {
        this.mContext = service;
        this.mExtensionManager = ExtensionManager.getInstance(service);
        HandlerThread handlerThread = new HandlerThread(TAG);
        handlerThread.start();
        this.mAsyncLooper = handlerThread.getLooper();
        this.mAsyncHandler = new Handler(this.mAsyncLooper);
        this.mExtensionManager.cleanupExtensions();
    }

    static {
        _createUpdateOperation(0);
        _createUpdateOperation(1);
        _createUpdateOperation(2);
        _createUpdateOperation(3);
        _createUpdateOperation(4);
        _createUpdateOperation(5);
        _createUpdateOperation(6);
    }

    private static void _createUpdateOperation(final int i) {
        UPDATE_OPERATIONS.put(i, new Operation() {
            @Override
            public void run(IExtension iExtension) {
                iExtension.onUpdate(i);
            }
        });
    }

    public void establishAndDestroyConnections(List<ComponentName> list) {
        Connection createConnection;
        HashSet<ComponentName> hashSet = new HashSet();
        hashSet.addAll(list);
        HashSet<ComponentName> hashSet2 = new HashSet();
        hashSet2.addAll(this.mExtensionConnections.keySet());
        for (ComponentName componentName : hashSet) {
            if (!hashSet2.contains(componentName) && (createConnection = createConnection(componentName, false)) != null) {
                this.mExtensionConnections.put(componentName, createConnection);
            }
        }
        hashSet2.removeAll(hashSet);
        for (ComponentName componentName2 : hashSet2) {
            destroyConnection(this.mExtensionConnections.get(componentName2));
            this.mExtensionConnections.remove(componentName2);
        }
    }

    private Connection createConnection(ComponentName componentName, final boolean z) {
        final Connection connection = new Connection();
        connection.componentName = componentName;
        connection.contentObserver = new ContentObserver(this.mClientThreadHandler) {
            @Override
            public void onChange(boolean z2) {
                ExtensionHost.this.logi("execute: onChagne");
                ExtensionHost.this.execute(connection.componentName,
                        ExtensionHost.UPDATE_OPERATIONS.get(4), UPDATE_COLLAPSE_TIME_MILLIS, (Object) 4);
            }
        };
        connection.hostInterface = makeHostInterface(connection);
        connection.serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName2, IBinder iBinder) {
                connection.ready = true;
                connection.binder = (IExtension) iBinder;
                ExtensionHost.this.logi("execute: onServiceConnected");
                ExtensionHost.this.execute(connection, new Operation() {
                    @Override
                    public void run(IExtension iExtension) {
                        try {
                            iExtension.onInitialize(connection.hostInterface, z);
                        } catch (SecurityException unused) {
                        }
                    }
                }, 0, (Object) null);
                if (!z) {
                    ExtensionHost.this.execute(connection.componentName, ExtensionHost.UPDATE_OPERATIONS.get(1), 0, (Object) null);
                }
                synchronized (connection.deferredOps) {
                    if (connection.ready) {
                        HashSet hashSet = new HashSet();
                        Iterator<Pair<Object, Operation>> it = connection.deferredOps.iterator();
                        while (it.hasNext()) {
                            Pair<Object, Operation> next = it.next();
                            if (next.first != null) {
                                if (!hashSet.contains(next.first)) {
                                    hashSet.add(next.first);
                                }
                            }
                            ExtensionHost.this.execute(connection, (Operation) next.second, 0, (Object) null);
                            it.remove();
                        }
                    }
                }
            }

            @Override
            public void onServiceDisconnected(final ComponentName componentName2) {
                connection.serviceConnection = null;
                connection.binder = null;
                connection.ready = false;
                ExtensionHost.this.mClientThreadHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        ExtensionHost.this.mExtensionConnections.remove(componentName2);
                    }
                });
            }
        };
        try {
            if (this.mContext.bindService(new Intent().setComponent(componentName), connection.serviceConnection, 1)) {
                return connection;
            }
            return null;
        } catch (SecurityException unused) {
            return null;
        }
    }

    private void destroyConnection(Connection connection) {
        if (connection.contentObserver != null) {
            this.mContext.getContentResolver().unregisterContentObserver(connection.contentObserver);
            connection.contentObserver = null;
        }
        connection.binder = null;
        this.mContext.unbindService(connection.serviceConnection);
        connection.serviceConnection = null;
    }

    public void execute(final Connection connection, final Operation operation, int i, Object obj) {
        final Pair pair = (i <= 0 || obj == null) ? null : new Pair(connection.componentName, obj);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    if (connection.binder == null) {
                        throw new RemoteException("Binder is unavailable.");
                    }
                    operation.run(connection.binder);
                } catch (RemoteException e) {
                    Log.e(ExtensionHost.TAG, "Couldn't execute operation; scheduling for retry upon service reconnection.", e);
                    synchronized (connection.deferredOps) {
                        connection.deferredOps.add(new Pair<>(pair, operation));
                    }
                }
            }
        };
        if (!connection.ready) {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    synchronized (connection.deferredOps) {
                        connection.deferredOps.add(new Pair<>(pair, operation));
                    }
                }
            });
            return;
        }
        if (pair != null) {
            this.mAsyncHandler.removeCallbacksAndMessages(pair);
        }
        if (i > 0) {
            this.mAsyncHandler.postAtTime(runnable, pair, SystemClock.uptimeMillis() + i);
        } else {
            this.mAsyncHandler.post(runnable);
        }
    }

    public void execute(ComponentName componentName, Operation operation, int i, Object obj) {
        Connection connection = this.mExtensionConnections.get(componentName);
        if (connection == null) {
            connection = createConnection(componentName, true);
            if (connection == null) {
                return;
            }
            this.mExtensionConnections.put(componentName, connection);
        }
        execute(connection, operation, i, obj);
    }

    private IExtensionHost makeHostInterface(final Connection connection) {
        return new IExtensionHost() {
            @Override
            public void publishUpdate(ExtensionData extensionData) {
                if (extensionData == null) {
                    extensionData = new ExtensionData();
                }
                ExtensionHost.this.mExtensionManager.updateExtensionData(connection.componentName, extensionData);
            }

            @Override
            public void addWatchContentUris(String[] strArr) {
                if (strArr == null || strArr.length <= 0 || connection.contentObserver == null) {
                    return;
                }
                ContentResolver contentResolver = ExtensionHost.this.mContext.getContentResolver();
                for (String str : strArr) {
                    if (!TextUtils.isEmpty(str)) {
                        contentResolver.registerContentObserver(Uri.parse(str), true, connection.contentObserver);
                    }
                }
            }

            @Override
            public void removeAllWatchContentUris() {
                ExtensionHost.this.mContext.getContentResolver().unregisterContentObserver(connection.contentObserver);
            }
        };
    }

    public void destroy() {
        establishAndDestroyConnections(new ArrayList());
        this.mAsyncLooper.quit();
    }

    private void loge(String str) {
        Log.e(TAG, str);
    }

    public void logi(String str) {
        Log.i(TAG, str);
    }

    public static class Connection {
        IExtension binder;
        ComponentName componentName;
        ContentObserver contentObserver;
        final Queue<Pair<Object, Operation>> deferredOps;
        IExtensionHost hostInterface;
        boolean ready;
        ServiceConnection serviceConnection;

        private Connection() {
            this.ready = false;
            this.deferredOps = new LinkedList();
        }
    }
}
